package com.slg.android.manyanime.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.manyanime.CartoonDetailActivity;
import com.slg.android.manyanime.R;
import com.slg.android.manyanime.adapter.CartoonCommonListAdapter;
import com.slg.android.manyanime.bean.CartoonNewest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by Thinkpad on 2015/3/11.
 */
public class CartoonNewestFragment extends Fragment implements PullToRefreshListView.OnRefreshListener2
        , ListView.OnItemClickListener

{

    public static String path = "http://manhua.api.61.com/?&pf=1&android_version=17&app_version=512&app_channel=百度&m=Cartoon&a=newListCartoon&limit=15&page=";
    public String currentPath = path + 1;

    @ViewInject(R.id.cartoon_newest_list)
    private PullToRefreshListView refreshListView;

    private HttpUtils httpUtils;

    private List<CartoonNewest> data;
    private CartoonCommonListAdapter adapter;
    private ListView trueList;

    public CartoonNewestFragment() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cartoon_newest, container, false);
        ViewUtils.inject(this, view);

        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        refreshListView.setOnRefreshListener(this);

        trueList = refreshListView.getRefreshableView();
        data = new LinkedList<CartoonNewest>();
        adapter = new CartoonCommonListAdapter(getActivity(), data);
        trueList.setAdapter(adapter);
        httpUtils = new HttpUtils();
        addData(data, currentPath);

        return view;
    }

    public void addData(final List<CartoonNewest> list, String url) {
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                        String str = stringResponseInfo.result;
                        if (str != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                JSONArray lists = jsonObject.getJSONArray("list");
                                for (int i = 0; i < lists.length(); i++) {
                                    JSONObject innerCartoon = lists.getJSONObject(i);

                                    CartoonNewest cartoon = new CartoonNewest();

                                    cartoon.parseJson(innerCartoon);

                                    if (!list.contains(cartoon)) {
                                        list.add(cartoon);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_LONG).show();
                    }
                }
        );
        trueList.setOnItemClickListener(this);
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        addData(data, path + 1);
        refreshListView.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        char c = currentPath.charAt(currentPath.length() - 1);
        int page = Integer.parseInt(String.valueOf(c)) + 1;
        currentPath = path + page;
        addData(data, currentPath);
        refreshListView.onRefreshComplete();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //获取listview的header的个数，应为点击的时候header占用了索引
        //真实的位置应该是postion-header
        int truePostion = position - trueList.getHeaderViewsCount();
        Intent intent = new Intent(getActivity(), CartoonDetailActivity.class);
        intent.putExtra("id", data.get(truePostion).getId());
        startActivity(intent);


    }
}
